#include "controller/UserLoginHandler.h"
#include "RapidJsonMacro.h"
#include "bean/User.h"
#include "model/UserModel.h"
#include "MD5.h"

UserLoginHandler::UserLoginHandler(const std::string& url):FastCgiHandler(url){

}

UserLoginHandler::~UserLoginHandler() {

}

void UserLoginHandler::doGet(const Fastcgipp::Http::Environment<char> &env, std::basic_ostream<char> &resp) {

}

void UserLoginHandler::doPost(const Fastcgipp::Http::Environment<char> &env, std::basic_ostream<char> &resp) {
    resp << "Content-Type: application/json; charset=utf-8\r\n\r\n";
    std::string out;

    auto it = env.posts.find("data");
    if(it == env.posts.cend()) {
        return ;
    }
    std::basic_string<char> data = it->second;

    rapidjson::Document d;
    rapidjson::Value obj(rapidjson::kObjectType);

    d.Parse<0>(data.c_str());
    if(d.HasParseError()) {
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","json parse error!");

        RapidJsonGetString(obj,out);

        resp << out;

        return ;
    }

    std::string username = json_check_string(d,"username");
    std::string password = json_check_string(d,"password");

    //验证用户名或者密码是否为空
    if(username.length() == 0 || password.length() == 0) {
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","username or password is empty!");

        RapidJsonGetString(obj,out);

        resp << out;

        return ;
    }

    std::shared_ptr<UserModel> userModelPtr(new UserModel("dbpool_app","cache_pool"));
    User user;

    if(!userModelPtr->getUser(username.c_str(),user)) {
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","user not exits!");

        RapidJsonGetString(obj,out);

        resp << out;

        return ;
    }

    //验证密码是否通过
    if(user.getpassword() != password) {
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","password is not correct!");

        RapidJsonGetString(obj,out);

        resp << out;

        return ;
    }

    //生成token
    MD5 md5;
    srand((unsigned)time(NULL));
    char temp[8];
    memset(temp,0,sizeof(temp));
    sprintf(temp,"%d",rand()%10000);
    std::string random(temp);
    std::string strToToken = username;
    strToToken = strToToken + password + random;
    std::string token = md5.getMd5(strToToken);

    //token 写入缓存
    userModelPtr->setTokenCache(username.c_str(),token.c_str());

    RapidJsonObjAddMember(d,obj,"code",0);
    RapidJsonObjAddStringMember(d,obj,"msg","login success!");
    RapidJsonObjAddStringMember(d,obj,"token",token.c_str());

    RapidJsonGetString(obj,out);

    resp << out;

}
